from mcp.server.fastmcp import FastMCP
import sys
import logging
import math
import random
import requests

# 配置日志
logger = logging.getLogger('CombinedServer')

# 修复Windows控制台的UTF-8编码问题
if sys.platform == 'win32':
    sys.stderr.reconfigure(encoding='utf-8')
    sys.stdout.reconfigure(encoding='utf-8')

# 创建一个统一的MCP服务器
mcp = FastMCP("myTools")

# ------------------------------
# 旺仔小乔粉丝相关功能
# ------------------------------
# Add a tool to get fan count for specific person
@mcp.tool()
def get_fan_count(celebrity_name: str) -> dict:
    """
    Returns the fan count for a given celebrity.
    Currently supports only '旺仔小乔'.
    """
    logger.info(f"Fetching fan count for: {celebrity_name}")
    
    if "旺仔小乔" in celebrity_name:
        return {
            "success": True,
            "celebrity": "旺仔小乔",
            "fan_count": "1795.0万",
            "unit": "万"
        }
    else:
        return {
            "success": False,
            "error": f"Fan count for '{celebrity_name}' is not available."
        }

# ------------------------------
# 灯光控制相关功能
# ------------------------------
# 模拟灯光状态（也可与Home Assistant同步）
# 模拟本地灯光状态（可用于缓存或降级）
light_status = {
    "living_room": False,
    "bedroom": False,
    "kitchen": False
}

# ========================
# 配置区（请根据你的环境修改）
# ========================

# Home Assistant 地址
HOME_ASSISTANT_URL = "http://192.168.0.183:8123"

# 获取方式：HA 用户设置 → Long-Lived Access Token
LONG_LIVED_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIxNmZmN2Q2YjNlYTA0ZTQyYWM5MmVhZmM4Zjc5YmVkMCIsImlhdCI6MTc0MTM0NTk1OCwiZXhwIjoyMDU2NzA1OTU4fQ.v1wnnhypVK4PsDMvVoKXxbQZ6ltNwkBoCAF_pnYoZSs"  #请替换为你的实际 Token

# 房间中文名到英文 key 的映射（用于本地状态）
ROOM_NAME_MAP = {
    "living_room": ["living_room", "客厅", "living", "living room", "livingroom"],
    "bedroom": ["bedroom", "卧室", "bed room", "卧房"],
    "kitchen": ["kitchen", "厨房"]
}

# 动作映射（支持中英文）
ACTION_MAP = {
    "on": ["on", "开", "打开", "开启", "turn on", "power on"],
    "off": ["off", "关", "关闭", "turn off", "power off"]
}

# 房间到 Home Assistant entity_id 的映射（必须真实存在）
ENTITY_MAP = {
    "living_room": "switch.esp01s",  # 请替换为你的实际设备ID
    # "bedroom": "switch.bedroom_lamp",
    # "kitchen": "switch.kitchen_light"
}

# 请求头（认证）
HEADERS = {
    "Authorization": f"Bearer {LONG_LIVED_TOKEN}",
    "Content-Type": "application/json"
}

# ========================
# MCP 工具函数
# ========================

@mcp.tool()
def control_light(room: str, action: str) -> dict:
    """
    控制指定房间的灯光，支持中文输入。
    参数：
        room: 房间名（支持中文，如“客厅”）
        action: 动作（支持“开”、“关”等）
    """
    # 查找匹配的房间 key
    target_room = None
    for key, aliases in ROOM_NAME_MAP.items():
        if room in aliases:
            target_room = key
            break

    if not target_room:
        all_rooms = [alias for aliases in ROOM_NAME_MAP.values() for alias in aliases]
        return {
            "success": False,
            "message": f"未知的房间：'{room}'。支持的房间：{all_rooms}"
        }

    # 查找动作
    target_action = None
    for act, aliases in ACTION_MAP.items():
        if action in aliases:
            target_action = act
            break

    if not target_action:
        valid_actions = [a for aliases in ACTION_MAP.values() for a in aliases]
        return {
            "success": False,
            "message": f"未知的动作：'{action}'。支持的动作：{valid_actions}"
        }

    # 获取设备实体 ID
    entity_id = ENTITY_MAP.get(target_room)
    if not entity_id:
        return {
            "success": False,
            "message": f"未配置房间 '{target_room}' 的设备 entity_id"
        }

    # 构建 Home Assistant API URL
    service = "turn_on" if target_action == "on" else "turn_off"
    api_url = f"{HOME_ASSISTANT_URL}/api/services/switch/{service}"

    # 请求数据
    payload = {"entity_id": entity_id}

    # 发送 POST 请求
    try:
        logger.info(f"向 Home Assistant 发送请求: {api_url} | 数据: {payload}")
        response = requests.post(
            url=api_url,
            json=payload,
            headers=HEADERS,
            timeout=10
        )

        if response.status_code in [200, 201]:
            # 更新本地状态
            light_status[target_room] = (target_action == "on")
            logger.info(f"成功控制 {target_room} ({action})")
            return {
                "success": True,
                "message": f"已{action} {room}的灯",
                "current_status": light_status.copy()
            }
        else:
            error_msg = response.text.strip()
            logger.error(f"HA 返回错误 [{response.status_code}]: {error_msg}")
            return {
                "success": False,
                "message": f"控制失败: HTTP {response.status_code} - {error_msg}"
            }

    except requests.exceptions.Timeout:
        logger.error("请求超时：Home Assistant 无响应")
        return {"success": False, "message": "请求超时"}
    except requests.exceptions.ConnectionError:
        logger.error("网络错误：无法连接到 Home Assistant")
        return {"success": False, "message": "网络连接失败"}
    except Exception as e:
        logger.error(f"请求异常: {e}")
        return {"success": False, "message": f"请求异常: {str(e)}"}

# 启动合并后的服务器
if __name__ == "__main__":
    mcp.run(transport="stdio")